package cn.symbio.basic.util;

import cn.symbio.pet.domain.Pet;
import cn.symbio.pet.service.IPetService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileWriter;

@Component
@Slf4j
public class FreemarkUtil {


    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${pagedir}")
    private String path;

    @Autowired
    private IPetService petService;


    private static FreemarkUtil freemarkUtil;

    /**
     * 初始化对象
     */
    @PostConstruct
    public void init() {
        freemarkUtil = this;
        freemarkUtil.freeMarkerConfigurer = this.freeMarkerConfigurer;
        freemarkUtil.path = this.path;
        freemarkUtil.petService = this.petService;
    }

    /**
     *
     * @param id 当前商品id
     * @throws Exception
     */
    public static void testHtml(Long id) throws Exception {
        // log.info(freemarkUtil.path);
        //创建模板技术的核心配置对象
        Configuration configuration = freemarkUtil.freeMarkerConfigurer.getConfiguration();
        //configuration.setClassForTemplateLoading(this.getClass(), "templates/");
        //ContextLoader loader = new ContextLoader();
        // TODO 有问题，找不到模板
        Template template = configuration.getTemplate("petDetail.ftl");
        //准备数据
        Pet pet = freemarkUtil.petService.findByPetId(id);
        //合并模板
        template.process(pet, new FileWriter(new File(freemarkUtil.path + "\\" + pet.getId() + ".html")));
    }
}
